package fr.castorhoz.isi_connectivity_widget;

import java.util.ArrayList;
import java.util.List;

import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public abstract class ConnBroadcastReceiver {

	protected Context context;
	
	private static List<ConnBroadcastReceiver> receivers = new ArrayList<ConnBroadcastReceiver>();
	
	/**
	 * Indicates if interesting changes occured.
	 * This flag must be changed to update appWidgets.
	 * Use hasChanged() to modify it
	 */
	private boolean hasChanged = false;
	
	public ConnBroadcastReceiver(Context context) {//ConnButton button) {
		super();
		//this.button = button;
		this.context = context;
		receivers.add(this);
		//registerItself(context);
	}
	
	protected void hasChanged() {
		hasChanged = true;
	}
	
	/**
	 * Indicates which action triggers this broadcast receiver
	 * @return
	 */
	public abstract String getBroadcastAction();
	
	/**
	 * Returns the widget name corresponding to this broadcast receiver
	 */
	protected abstract String getWidgetName();
	
	/**
	 * Methods to implement to deal with what must be done oO
	 * @param context
	 * @param intent
	 */
	public abstract void doOnReceive(Context context, Intent intent);

	/**
	 * Obtain the list of widgets that listen to the receiver
	 * @return
	 */
	protected abstract List<Integer> getAppWidgetIds();
	
	/**
	 * DO NOT OVERRIDE THIS METHOD. Override doOnReceive instead.
	 * This methods allows common treatment for all broadcastReceivers
	 */
	final public void onReceive(Context context, Intent intent) {
		Log.d(this.getClass().getName(), "broadcast action received : "+intent.getAction());
		doOnReceive(context, intent);
		
		/*
		 * update all widgets which listen to this receiver
		 */
		Log.i(this.getClass().getName(), "updating appwidgets with hadChanged value : "+hasChanged);
		if (hasChanged) {
			hasChanged = false;
			AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
			for (int appWidgetId : getAppWidgetIds()) {
				ConnWidget.updateAppWidget(context, appWidgetManager, appWidgetId);
			}
		}
	}

	@Override
	protected void finalize() throws Throwable {
		Log.e(this.getClass().getName(), "Object destructed");
		super.finalize();
	}


}
